//
//  SEChatBaseCell.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/9.
//

import UIKit

let kChatAvatarMarginLeft: CGFloat = 15
let kChatAvatarMarginTop: CGFloat  = 0
let kChatAvatarWidth: CGFloat      = 42

class SEChatBaseCell: UITableViewCell {
    
    weak var delegate: SEChatCellDelegate?
    
    var viewModel: SEChatViewModel?
    
    // MARK: - life cycle
    
    override func prepareForReuse() {
        avatarImageView.image = nil
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        selectionStyle = .none
        contentView.backgroundColor = .clear
        backgroundColor = .clear
    }
    
    override func layoutSubviews() {
        guard let vm = viewModel else { return }
        
        if vm.fromMe {
            avatarImageView.left = UIScreen.screenWidth - kChatAvatarWidth - kChatAvatarMarginLeft
        } else {
            avatarImageView.left = kChatAvatarMarginLeft
        }
    }
    
    func update(with viewModel: SEChatViewModel) {
        self.viewModel = viewModel
        
        avatarImageView.kf.setAvatarImage(urlString: viewModel.avatar, placeholder: viewModel.avatarPlaceholder)
        
        switch viewModel.chatRecord.messageSendStatus {
        case .success:
            activityIndicator.isHidden = true
            activityIndicator.stopAnimating()
            resendButton.isHidden = true
        case .failure:
            activityIndicator.isHidden = true
            activityIndicator.stopAnimating()
            resendButton.isHidden = false
        case .sending:
            activityIndicator.isHidden = false
            activityIndicator.startAnimating()
            resendButton.isHidden = true
        }
    }
    
    @IBAction func resendTapped() {
        delegate?.cellResendTapped(self)
    }
    
    @IBOutlet weak var avatarImageView: UIImageView! {
        didSet {
            avatarImageView.width = kChatAvatarWidth
            avatarImageView.height = kChatAvatarWidth
            avatarImageView.layer.cornerRadius = kChatAvatarWidth / 2
        }
    }
    
    @IBOutlet weak var resendButton: UIButton! {
        didSet {
            resendButton.isHidden = true
            resendButton.width = 20
            resendButton.height = 20
        }
    }
    
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView! {
        didSet {
            activityIndicator.width = 20
            activityIndicator.height = 20
        }
    }
}
